<?php
error_reporting(E_ERROR | E_PARSE);
//test_house script script created by Robert Cox on August 1st 2011
//Commandline Usage: test_actiontracking.php commandline (debug)
//URL Usage: http://.../../test_actiontracking.php?web=1              <= normal mode
//      -or- http://.../../test_actiontracking.php?web=1&debug=1      <= debug mode

// set start time
require("/http/matchtest/classes/class.phpmailer.php");

$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;


if(isset($_GET['debug'])){
                $debug = TRUE;
                $GLOBALS["debug"] = TRUE;
        } else {
                unset($debug);
        }

if(isset($_GET['web'])){
                $web = TRUE;
                $GLOBALS["web"] = TRUE;
        } else {
                unset($web);
        }


if (isset($debug)) { 
	echo "<br>* * * * *  D E B U G = O N * * * * *<br>";
	if (isset($web)) { 
		echo "<br>* * * * *  W E B = O N  * * * * *<br>";}
}

$status = "pending";
$testname = "Unique Visitor Test";
$testshortname = "uniquevisitortest";
$testdesc = "Verify that Unique Visitor Reporting is Working";
$testurl = "test_uniquevisitor.php";
$testtime = time();
$iyesterday = $testtime-86400;
$ilifetimestart = mktime(0,0,0,10,1,2011);

$today = date("F j, Y, g:i a");
$hour = date("G");
$datestamp = date("Y-m-d");
$yesterday = date("Y-m-d",$iyesterday);
$monthly = date("Y-m-01",$iyesterday);
$random = rand();

$dailyuv_expected_results = 10;
$sumserved_expected_results = 100;
$lifetimeuv_expected_results = ((ceil(($iyesterday-$ilifetimestart)/86400)*10)+49);
if($debug){ echo "Yesterday: ".$iyesterday."<br>"; }
if($debug){ echo "ilifetimestart: ".$ilifetimestart."<br>"; }
if($debug){ echo "lifetimeuv_expected_results: ".$lifetimeuv_expected_results."<br>"; }
$monthly_expected_results = date("j",$iyesterday)*10;


// setup command line args (commandline only)
if (isset($argv[1])) { $commandline = $argv[1]; unset($debug);} 

// Username, password and schema for the database connection.
$username="aimatch";
$password="RMSAdmin";
$database="canary";

// Connect to the database and run the query
mysql_connect('w19',$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

// Retrieve Unique Visitor Numbers from the database
//-------- Daily Query ---------------
$query_dailyuv = "select served_uniques from uvdaily where date=\"".$yesterday."\" and flight_id=13";

if($debug){ echo "Daily UV Query: <br>".$query_dailyuv."<br>"; }
// Retrieve the query results
$dailyuv_result=mysql_query($query_dailyuv);

// Determine the number of rows in the result set.
if($dailyuv_result){
    $daily_served_uniques=mysql_result($dailyuv_result,0,"served_uniques"); }
else {
    $daily_served_uniques=0; }
	
if($daily_served_uniques == $dailyuv_expected_results){
	$daily_status = "pass";
	$daily_status_html = "<font color=green><b>pass</b></font>";
}
else{
	$daily_status = "fail";
	$daily_status_html = "<font color=red><b>fail</b></font>";
}

// Retrieve Unique Visitor Numbers from the database
//-------- Monthly Query ---------------
$query_monthlyuv = "select served_uniques from uvmonthly where date=\"".$monthly."\" and flight_id=13";

if($debug){ echo "Daily UV Query: <br>".$query_monthlyuv."<br>"; }
// Retrieve the query results
$monthlyuv_result=mysql_query($query_monthlyuv);

// Determine the number of rows in the result set.
if($monthlyuv_result){
    $monthly_served_uniques=mysql_result($monthlyuv_result,0,"served_uniques"); }
else {
    $monthly_served_uniques=0; }
	
if($monthly_served_uniques == $monthly_expected_results){
	$monthly_status = "pass";
	$monthly_status_html = "<font color=green><b>pass</b></font>";
}
else{
	$monthly_status = "fail";
	$monthly_status_html = "<font color=red><b>fail</b></font>";
}

//-------- Lifetime Query ---------------
$query_lifetimeuv = "select served_uniques from uvlifetime where flight_id=13";

if($debug){ echo "Daily UV Query: <br>".$query_lifetimeuv."<br>"; }
// Retrieve the query results
$lifetimeuv_result=mysql_query($query_lifetimeuv);

// Determine the number of rows in the result set.
if($lifetimeuv_result){
    $lifetime_served_uniques=mysql_result($lifetimeuv_result,0,"served_uniques"); }
else {
    $lifetime_served_uniques=0; }
	
if($lifetime_served_uniques == $lifetimeuv_expected_results){
	$lifetime_status = "pass";
	$lifetime_status_html = "<font color=green><b>pass</b></font>";
}
else{
	$lifetime_status = "fail";
	$lifetime_status_html = "<font color=red><b>fail</b></font>";
}

//-------- Sum(Served) Query ---------------
$query_imps = " select date,flight_id,sum(served) as sumserved from bigsum where flight_id=13 and date=\"".$yesterday."\" ";

if($debug){ echo "Daily UV Query: <br>".$query_imps."<br>"; }
// Retrieve the query results
$imps_result=mysql_query($query_imps);

// Determine the number of rows in the result set.
if($imps_result){
    $sumserved=mysql_result($imps_result,0,"sumserved"); }
else {
    $sumserved=0; }
	
if($sumserved == $sumserved_expected_results){
	$sumserved_status = "pass";
	$sumserved_status_html = "<font color=green><b>pass</b></font>";
}
else{
	$sumserved_status = "fail";
	$sumserved_status_html = "<font color=red><b>fail</b></font>";
}

$i=0;
$spaces = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
$commandline_output = $commandline_output."\n--------------------------------------------------------------------------------------------------------------------------\n"; 
$web_output = ""; 
$commandline_output = "\nUnique Visitor Test Results for $today\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>Daily Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):&nbsp;&nbsp;&nbsp;</b><font color=blue>".$daily_served_uniques."</font></font><br>"; 
$commandline_output = $commandline_output."Daily Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):  ".$daily_served_uniques."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."Expected Results:&nbsp;&nbsp;&nbsp;</b><font color=blue>".$dailyuv_expected_results."</font></font><br>";
$commandline_output = $commandline_output."                                                       Expected Results:  ".$dailyuv_expected_results."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Test Results:&nbsp;&nbsp;&nbsp;</b>".$daily_status_html."</font><br><br>";
$commandline_output = $commandline_output."                                                           Test Results:  ".$daily_status."\n\n"; 

$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>Monthly Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):&nbsp;&nbsp;&nbsp;</b><font color=blue>".$monthly_served_uniques."</font></font><br>"; 
$commandline_output = $commandline_output."Monthly Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):  ".$monthly_served_uniques."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Expected Results:&nbsp;&nbsp;&nbsp;</b><font color=blue>".$monthly_expected_results."</font></font><br>";
$commandline_output = $commandline_output."                                                       Expected Results:  ".$monthly_expected_results."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Test Results:&nbsp;&nbsp;&nbsp;</b>".$monthly_status_html."</font><br><br>";
$commandline_output = $commandline_output."                                                           Test Results:  ".$monthly_status."\n\n"; 

$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>Lifetime Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):&nbsp;&nbsp;&nbsp;</b><font color=blue>".$lifetime_served_uniques."</font></font><br>"; 
$commandline_output = $commandline_output."Daily Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):  ".$lifetime_served_uniques."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Expected Results:&nbsp;&nbsp;&nbsp;</b><font color=blue>".$lifetimeuv_expected_results."</font></font><br>";
$commandline_output = $commandline_output."                                                       Expected Results:  ".$lifetimeuv_expected_results."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Test Results:&nbsp;&nbsp;&nbsp;</b>".$lifetime_status_html."</font><br><br>";
$commandline_output = $commandline_output."                                                           Test Results:  ".$lifetime_status."\n\n"; 

$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Total Daily Impressions Served for UNIQUE VISITOR TRACKING FLIGHT:&nbsp;&nbsp;&nbsp;</b><font color=blue>".$sumserved."</font></font><br>"; 
$commandline_output = $commandline_output."Daily Unique Visitors for UNIQUE VISITOR TRACKING FLIGHT (flight.id 13):  ".$sumserved."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;Expected Results:&nbsp;&nbsp;&nbsp;</b><font color=blue>".$sumserved_expected_results."</font></font><br>";
$commandline_output = $commandline_output."                                                       Expected Results:  ".$sumserved_expected_results."\n"; 
$web_output = $web_output."<font face=\"Tahoma\" size=\"4\"><b>".$spaces."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Test Results:&nbsp;&nbsp;&nbsp;</b>".$sumserved_status_html."</font><br><br>";
$commandline_output = $commandline_output."                                                           Test Results:  ".$sumserved_status."\n\n"; 

if(($daily_status == "pass") && ($monthly_status == "pass") && ($lifetime_status == "pass") && ($sumserved_status == "pass")) {
	$web_test_status = "<br><font face=\"Tahoma\" size=\"5\"><b>(<font color=green>Passed</font>) Unique Visitor Test Results for $today</b></font><br><hr>"; 
	$commandline_test_status = "(Passed) Unique Visitor Test Results for $today\n---------------------------\n"; 
	$status = "pass"; } 
else {
	$web_test_status = "<br><font face=\"Tahoma\" size=\"5\"><b>(<font color=red>Failed</font>) Unique Visitor Test Results for $today</b></font><br><hr>"; 
	$commandline_test_status = "(Failed) Unique Visitor Test Results for $today\n---------------------------\n"; 
	$status = "fail"; } 



$to_file = $commandline_test_status.$commandline_output;

if (isset($web)) { 
	echo $web_test_status.$web_output; }
else {
	echo $to_file; }


$filestatus = WriteResultsFile($status,$testshortname,$testname,$testdesc,$testurl,$testtime,$web,$to_file);

//================= Functions =================
	
function WriteResultsFile($status,$testshortname,$testname,$testdesc,$testurl,$testtime,$web,$to_file){
//	$debug = 1;
	// Setup the archival file name for the test
	$datestamp = date("YmdGis");
	$directory = "/http/matchtest/archived_results/uniquevisitortest/";
	if(!is_dir($directory)){
		if(!mkdir($directory, 0777)) {
			die('Failed to create directory: '.$directory);
		}
	}

	// Write out the information to the testresults.txt file.
	$lines = file('/http/matchtest/testresults.txt');
	$numitems = count($lines);

	// Loop through our array, show HTML source as HTML source; and line numbers too.

	if (isset($debug)) { echo "<br><pre>HTTP Response Output:<br><br>"; print_r($lines); echo "</pre><br>"; }

	$newfile = $lines[0];
	$i=1;
	while($i <= $numitems) {
		$pieces = explode("|",$lines[$i]);
		if($testname == $pieces[1]){
			$replaced_line = $status."|".$testname."|".$testdesc."|".$testurl."|".$testtime."\n";
			$newfile = $newfile.$replaced_line;
		}
		else{
			$newfile = $newfile.$lines[$i];
		}
		$i++;
	}

	if (isset($debug)) { echo "<br><pre>New File Output:<br><br>"; print_r($newfile); echo "</pre><br>"; }

	$fp = fopen('/http/matchtest/testresults.txt', 'w');

	fwrite($fp, $newfile);
	fclose($fp);

// Write out results of the test to a file 
	if (isset($debug)) { echo "Filename: ".$directory.$testshortname.".web.".$status.".".$datestamp.".".$testtime.".txt<br>"; }

	if (isset($web)) { $testfilename = $directory.$testshortname.".web.".$status.".".$datestamp.".".$testtime.".txt"; }
	else { $testfilename = $directory.$testshortname.".commandline.".$status.".".$datestamp.".".$testtime.".txt"; }

	if (!$fp1 = fopen($testfilename,'w')) {
		echo "Cannot open file ($testfilename)";
		exit;
	}

	fwrite ($fp1,$to_file."\n\n");
	fclose($fp1);

	return 0;
}

function MakeAdCall($url) {
	$UserAgent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16";

    // initilize the curl call
    $ch = curl_init();
    // set useragent
    curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
    // Set curl to use $url for http call
    curl_setopt($ch, CURLOPT_URL, $url);
    // show client headers
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // have curl put X-Forwarded-For into headers
    curl_setopt($ch,CURLOPT_HTTPHEADER, $client_headers);
    // store results as the return of curl_exec
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    // Follow redirects
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);		
    // if HTML error 400 over over, fail
    curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);

    $output = curl_exec($ch);
    if (isset($debug)) { echo "<br><pre>HTTP Response Output:<br><br>"; print_r($output); echo "</pre><br>"; }
    //close curl connection
    curl_close($ch);

return $output;
}


function MakeOutputArray($output){
        $output_array = preg_split('/[\n]/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        if (isset($debug)) { echo "<br><pre>HTTP Response Output (array):<br><br>"; print_r($output_array); echo "</pre><br>"; }

return $output_array;
}


function TraceInfo($output,$string,$debug) {

        $line_match = array_values(preg_grep("/$string/", $output));
            if (isset($GLOBALS["debug"])) { echo "DEBUG - string:  ".$string."<br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - output:  <br><pre>"; print_r($output); echo "</pre><br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - line_match:<br><pre>"; print_r($line_match); echo "</pre><br>";}
        if(stripos($line_match[0], " = ")){
			$explode = explode(" = ", $line_match[0]); }
        if(stripos($line_match[0], ":")){
			$explode = explode(":", $line_match[0]); }
        if(stripos($line_match[1], ">>>>")){
			$result = $line_match[1]; }
        if (isset($GLOBALS["debug"])) { echo "DEBUG - result:  ".$result."<br>";}
		return $result;
}

function GetFormattedOutput($output_array, $web,$debug){
        $http_response = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);
//        if (isset($debug)) { echo "<br>DEBUG - HTTP CODE/TEXT: $http_return_code / $http_return_text<br>"; }

        /* check code = 200 or 302 and text equal OK, anything else we have an error */

        if (($http_return_text != "OK" || $http_return_code != "200")&&($http_return_text != "Relocate" || $http_return_code != "302")) {
//            if (isset($debug)) { echo "***** ALERT - HTTP CODE/TEXT: ".trim($http_response[0])." *****<br>"; }
				echo "HTTP return code/text was not 200/OK". trim($http_response[0])."<br>";
                die;
        }
		
		// count the number of elements in the response array
		$num_elements = count($output_array);
//        if (isset($debug)) { echo "The Number Of Elements in the OUTPUT Array are: ".$num_elements." <br>"; }
		
		// format the items in the array as a long concatenated string.
		$y=0;
		while($y <= $num_elements){
			$formatted_output = $formatted_output.$output_array[$y]."\n";
			$formatted_output_web = $formatted_output_web.$output_array[$y]."<br>";
			$y++;
		}
//        if (isset($debug)) { echo "The Formatted contents of OUTPUT are: ".$formatted_output_web." *****<br>"; }
		
		if($web) {
			return $formatted_output_web; }
		else {
			return $formatted_output; }
}

function CheckResponse($text1,$text2,$text3,$output,$SearchString,$web){

		$response = print_r($output,TRUE);
		if(stripos($output, $SearchString)){
			$message1 = "***** SUCCESS - ".$text1;
			$message2 = $text2;
			$message3 = $text3;
			$web_message1 = $message1."<br>";
			$cl_message1 = $message1."\n"; 
            $web_message2 = $message2."";
			$cl_message2 = $message2."\n"; 
			$web_message3 = "<pre>".$message3."<br><br><textarea readonly name=\"text\" style=\"width: 1300px; height: 300px\">".$response."</textarea></pre><br>"; 
			$cl_message3 = "".$message3."\n".$response."\n"; 
			$status = "pass";
        }
        else {
			$message1 = "***** ALERT - Targeting doesn't match. Targeting IS NOT WORKING: $TraceTargeting";
			$message2 = "***** Writing out failure to testresults.txt";
			$message3 = "HTTP Response Output:";
            $web_message1 = $message1."<br>"; 
            $cl_message1 = $message1."\n"; 
            $web_message2 = $message2."";
            $cl_message2 = $message2."\n";
			$web_message3 = "<br><pre>".$message3."<br><br>".$response."</pre><br>"; 
			$cl_message3 = "\n".$message3."\n".$response."\n"; 
			$status = "fail";			
		}
	return array($status,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3);
}

function CheckClickResponse($text1,$text2,$text3,$output_array,$SearchString,$web,$debug){

        $http_response1 = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response1[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);

        $http_response2 = array_values(preg_grep("/^Location:/", $output_array));
        $http_array2 = explode(" ",$http_response2[0]);
        $http_location_destination = trim($http_array2[1]);
	
        if (isset($debug)) { echo "The Elements of the HTTP Respons Array are: <br>
		http_return_code: ".$http_return_code."<br>
		http_return_text: ".$http_return_text."<br>
		http_location_destination: ".$http_location_destination."<br>
		*****<br>"; }

        if (isset($debug)) { echo "SearchString is: ".$SearchString."<br>"; }
		
		
        if(stripos($http_location_destination, $SearchString)){
			$message1 = "***** SUCCESS - ".$text1;
			$message2 = $text2;
			$message3 = $text3;
			if (isset($web)) { $web_message1 = $message1."<br>";}
			else { $cl_message1 = $message1."\n"; }
            if (isset($web)) { $web_message2 = $message2."";}
			else { $cl_message2 = $message2."\n"; }
			if (isset($web)) { $web_message3 = $message3." ".$http_location_destination."<br><br>"; }
			else { $cl_message3 = $message3." ".$http_location_destination."\n"; }
			$status = "pass";
        }
        else {
			$message1 = "***** ALERT - Targeting doesn't match. Targeting IS NOT WORKING: $TraceTargeting";
			$message2 = "***** Writing out failure to testresults.txt";
			$message3 = "HTTP Response Output:";
            if (isset($web)) { $web_message1 = $message1."<br>"; }
            else { $cl_message1 = $message1."\n"; }
            if (isset($web)) { $web_message2 = $message2."";}
            else { $cl_message2 = $message2."\n";}
			if (isset($web)) { $web_message3 = $message3." ".$http_location_destination."<br><br>"; }
			else { $cl_message3 = $message3." ".$http_location_destination."\n"; }
			$status = "fail";			
		}
	return array($status,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3);
}

?>
